import {ref, computed} from "vue";
export default function useEditTodo(todosRef) {
    const editingTodoRef = ref(null); //当前正在修改的是哪一个todo
    let originTitle = null;
    const editTodo = (todo) => {
        originTitle = todo.title;
        editingTodoRef.value = todo;
    }
    const doneEdit = (todo) => {
        editingTodoRef.value = null;
        const title = todo.title.trim();
        if(title) {
            todo.title = title;
        } else {
            //删除
            todosRef.value.splice(todosRef.value.indexOf(todo), 1);
        }
    }
    const canceEdit = (todo) => {
        todo.title = originTitle;
        editingTodoRef.value = null;
        
    }
    const allDoneRef = computed({
        get() {
            return todosRef.value.filter((item) => !item.completed).length === 0;
        },
        set(checked) {
            todosRef.value.forEach((todo) => {
                todo.completed = checked;
            });
        }
    })
    return {
        editingTodoRef,
        editTodo,
        doneEdit,
        canceEdit,
        allDoneRef,
    }
}